import 'package:flutter/material.dart';
import 'package:mi_mang_flutter/api/email_api.dart';
import 'package:mi_mang_flutter/page/setting/setting_router.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/routers/fluro_navigator.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';
import 'package:mi_mang_flutter/utils/toast_util.dart';

class EmailBindPage extends StatefulWidget {
  EmailBindPage({Key? key}) : super(key: key);

  @override
  _EmailBindPageState createState() => _EmailBindPageState();
}

class _EmailBindPageState extends State<EmailBindPage> {
  TextEditingController _emailController = TextEditingController();

  /// 按钮是否可点击
  bool _isClick = false;

  @override
  void initState() {
    super.initState();
    _emailController.addListener(() {
      if (_emailController.text.isNotEmpty) {
        _isClick = true;
      } else {
        _isClick = false;
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(i18n(context).bindEmail),
        centerTitle: true,
      ),
      body: Padding(
        padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
        child: Column(
          children: <Widget>[
            TextField(
              controller: _emailController,
            ),
            Gaps.vGap25,
            ElevatedButton(
              onPressed: _isClick ? _sendCode : null,
              child: Container(
                height: 45,
                width: double.infinity,
                alignment: Alignment.center,
                child: Text(i18n(context).next),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 发送绑定邮箱验证码
  void _sendCode() {
    // showDialog(
    //   context: context,
    //   barrierDismissible: false,
    //   builder: (_) => SMSVerifyDialog(email: emailController.text.trim()),
    // );

    /// 验证是否是邮箱格式
    if (!isEmail(_emailController.text.trim())) {
      Toast.showWarn("请输入正确的邮箱格式！");
      return;
    }

    EmailApi.sendEmailCode(_emailController.text.trim()).then((val) {
      NavigatorUtils.push(
        context,
        "${SettingRouter.accountVerificationCode}?email=${_emailController.text.trim()}",
        replace: true,
      );
    });
  }

  /// 判断是否是email格式
  static bool isEmail(String email) {
    /// Regex of email.
    String regexEmail = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$";
    return matches(regexEmail, email);
  }

  /// 判断某个字符串是否匹配正则表达式
  static bool matches(String regex, String input) {
    if (input.isEmpty) return false;
    return new RegExp(regex).hasMatch(input);
  }
}
